﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WinFormsApp1
{
    public class FormBaseScriptCallback : ScriptCallback
    {
        [DllImport("user32.dll")]
        public static extern bool ReleaseCapture();

        [DllImport("user32.dll")]
        public static extern bool SendMessage(IntPtr hwnd, int wMsg, int wParam, int lParam);

        private const int VM_NCLBUTTONDOWN = 0XA1;//定义鼠标左键按下
        private const int HTCAPTION = 2;

        public FormBaseScriptCallback(FormBase bindingForm) : base(bindingForm) { }

        public void StartDrag()
        {
            if (BindingForm == null) return;
            //为当前应用程序释放鼠标捕获
            ReleaseCapture();
            //发送消息 让系统误以为在标题栏上按下鼠标
            SendMessage((IntPtr)BindingForm.Handle, VM_NCLBUTTONDOWN, HTCAPTION, 0);
        }

        public void EndDrag()
        {
            //为当前应用程序释放鼠标捕获
            ReleaseCapture();
        }

        public void Close()
        {
            if (BindingForm != null) BindingForm.Close();
        }

        public void Minimize()
        {
            if (BindingForm != null) BindingForm.WindowState = FormWindowState.Minimized;
        }

        public void Maximize()
        {
            if (BindingForm != null)
            {
                if (BindingForm.WindowState == FormWindowState.Maximized)
                    BindingForm.WindowState = FormWindowState.Normal;
                else
                    BindingForm.WindowState = FormWindowState.Maximized;
            }
        }
    }
}
